import { OrderModel } from '../../../../models/order'

const orderModel = new OrderModel()

import { PayModel } from '../../../../models/pay.js'

import { encryptString } from '../../../../utils/index.js'

var pingpp = require('../../../../utils/pingpp.js')

import { AppModel } from '../../../../models/app.js'
const appModel = new AppModel()

const ModelPay = new PayModel()

const App = getApp()

Page({
  /**
     * 页面的初始数据
     */
  data: {
    navs: ['全部', '待付款', '待发货', '拣货中', '已发货', '已完成', '已撤销'],
    winHeight: '',
    currentTab: 0,
    scrollLeft: 0,
    pageIndex: 1,
    pageSize: 5,
    loading: false,
    hasNext: true,
    empty: false,
    locked:false,
    nowTime: new Date().getTime(),
    channel: 8, //支付渠道：1支付宝App支付，2支付宝扫码支付，3微信App支付，4微信公众号支付，5微信扫码支付，6余额支付，7智荟金桥，8微信小程序支付
    orderList: [],
    orderstatus: [
      {},
      {
        btnArr: [{ name: '撤销订单', class: 'undo' }, { name: '支付', class: 'pay' }]
      },
      {},
      {},
      {
        btnArr: [
          { name: '确认收货', class: 'confirm' },
          { name: '查看物流', class: 'logistics' }
        ]
      },
      { btnArr: [{ name: '去评价', class: 'evaluate' }] },
      { btnArr: [{ name: '删除订单', class: 'dele' }] }
    ],
    statusBarHeight: App.globalData.statusBarHeight,
    isTabbar:false
  },

  // switchTab:function(event){
  //   let currentId = event.currentTarget.dataset.current
  //   this.setData({
  //     currentTab:currentId
  //   })
  // },
  /**
     * 生命周期函数--监听页面加载
     */
  tapToDetail: function(event) {
    const orderId = event.currentTarget.dataset.orderid
    wx.navigateTo({
      url: '/pages/account/order/detail/index?orderid=' + orderId
    })
  },

  checkCor: function() {
    if (this.data.currentTab > 4) {
      this.setData({
        scrollLeft: 300
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },

  switchTab: function(e) {
    this.setData({
      currentTab: e.detail.current,
      pageIndex: 1,
      empty: false
    })
    this.checkCor()
    this.getOrderList()
  },

  swichNav: function(e) {
    var cur = e.currentTarget.dataset.current
    if (this.data.currentTab == cur) {
      return false
    } else {
      this.setData({
        currentTab: cur,
        pageIndex: 1,
        empty: false
      })
      this.getOrderList()
    }
  },

  //获取订单列表
  getOrderList: function() {
    //检查是否上锁
    if(this.data.locked){
      return;
    }
    var self = this
    self.data.locked = true
    self.setData({
      orderList: [],
      locked:self.data.locked
    })
    const params = {
      orderStatus: self.data.currentTab,
      pageIndex: self.data.pageIndex,
      pageSize: self.data.pageSize
    }

    orderModel
      .getOrderList(params)
      .then(res => {
        if (res.data.orderList.length == 0) {
          self.data.empty = true
        } else {
          self.data.empty = false
        }
        self.setData({
          empty: self.data.empty,
          orderList: res.data.orderList,
          hasNext: res.data.hasNext,
          loading: false,
          locked:false
        })
        wx.stopPullDownRefresh()
      })
      .catch()
  },

  //撤销订单
  undo: function(e) {
    const self = this
    wx.showModal({
      title: '提示',
      content: '是否确认撤销订单?',
      success: function(res) {
        if (res.confirm) {
          //确认收货，发送收货请求
          const params = {
            orderId: e.currentTarget.dataset.id
          }
          orderModel
            .revokeOrder(params)
            .then(res => {
              App.WxService.showToast({
                title: '撤销成功',
                icon: 'none'
              })
              self.getOrderList()
            })
            .catch()
        } else if (res.cancel) {
          console.log('取消撤销订单')
        }
      }
    })
  },

  //支付订单
  pay: function(e) {
    var info = e.currentTarget.dataset.info
    const self = this
    const orderIds = []
    //订单加密
    orderIds.push(encryptString(info.id, 1))

    const params = {
      orderIds: orderIds,
      amount: (info.orderAmount / 100).toFixed(2),
      channel: self.data.channel,
      open_id: App.globalData.userInfo.openId
    }

    ModelPay.pay(params)
      .then(res => {
        pingpp.createPayment(res.data.order, function(result, err) {
          if (result == 'success') {
            // 只有微信公众号 (wx_pub)、微信小程序（wx_lite）、QQ 公众号 (qpay_pub)支付成功的结果会在这里返回，其他的支付结果都会跳转到 extra 中对应的 URL
            // 查询支付结果
            const params = { pid: res.data.pid }
            setTimeout(function() {
              return ModelPay.payResult(params).then(res => {
                if (res.status == 200) {
                  // 查询支付结果
                  App.WxService.redirectTo(
                    '/packCart/pages/payOrder/success/index?pid=' + res.data.payCode
                  )
                
                }
              })
            }, 1000)
          } else if (result == 'fail') {
            App.WxService.showToast({
              title: '支付失败',
              icon: 'none'
            })
            self.getOrderList()
            // Ping++ 对象 object 不正确或者微信公众号/微信小程序/QQ公众号支付失败时会在此处返回
          } else if (result == 'cancel') {
            // 微信公众号、微信小程序、QQ 公众号支付取消支付
            App.WxService.showToast({
              title: '取消支付',
              icon: 'none'
            })
            setTimeout(function() {
              self.onLoad()
            }, 1000)
          }
        })
      })
    
      .catch(err => {
        console.log(err)
      })
  },

  //确认收货
  confirm: function(e) {
    const self = this
    wx.showModal({
      title: '提示',
      content: '是否确认收货？',
      success: function(res) {
        if (res.confirm) {
          //确认收货，发送收货请求
          const params = {
            orderId: e.currentTarget.dataset.id
          }
          orderModel
            .confirmGoods(params)
            .then(res => {
              if (res.info == 'success') {
                App.WxService.showToast({
                  title: '确认收货成功',
                  icon: 'none'
                })
                wx.redirectTo({
                  url:
                    '/pages/account/order/confirm/index?orderId=' +
                    params.orderId +
                    '&evaluateGold=' +
                    res.data.evaluateGold
                })
              }
            })
            .catch()
        } else if (res.cancel) {
          console.log('取消确认收货')
        }
      }
    })
  },

  //查看物流
  logistics: function(e) {
    const orderId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/account/order/detail/index?orderid=' + orderId
    })
  },

  //去评价--批量评价传2
  evaluate: function(e) {
    const orderId = e.currentTarget.dataset.id
    const evaluateNum = 2
    wx.navigateTo({
      url:
        '/pages/account/order/comment/index?orderId=' +
        orderId +
        '&evaluateNum=' +
        evaluateNum
    })
  },

  //删除订单
  dele: function(e) {
    const self = this
    wx.showModal({
      title: '提示',
      content: '确定要删除订单么？',
      success(res) {
        if (res.confirm) {
          const params = {
            orderId: e.currentTarget.dataset.id
          }
          orderModel
            .delOrder(params)
            .then(res => {
              App.WxService.showToast({
                title: '删除成功',
                icon: 'none'
              })
              self.getOrderList()
            })
            .catch()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  onLoad: function(options) {
    var that = this
    wx.getSystemInfo({
      success: function(res) {
        // console.log(res.windowHeight)
        let clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth
        var calc = clientHeight * rpxR - 86
        // console.log(calc)
        that.setData({
          winHeight: calc
        })
      }
    })

    //获取传参信息,查看不同状态的订单列表
    //判断是查看全部订单列表还是某一状态列表
    if (options) {
      if (options.index) {
        this.setData({
          currentTab: options.index
        })
      }
      this.getOrderList()
    } else {
      this.getOrderList()
    }
  },

  /**
     * 生命周期函数--监听页面初次渲染完成
     */
  onReady: function() {},

  /**
     * 生命周期函数--监听页面显示
     */
  onShow: function() {
    // this.getOrderList();
  },

  /**
     * 生命周期函数--监听页面隐藏
     */
  onHide: function() {},

  /**
     * 生命周期函数--监听页面卸载
     */
  onUnload: function() {},

  /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
  onPullDownRefresh: function() {
    App.WxService.showToast({
      title: '下拉刷新1',
      icon: 'none'
    })
    this.setData({
      pageIndex: 1,
      pageSize: 5
    })
    this.getOrderList()
  },

  //加载更多
  loadMore(isPull) {
    const self = this
    if (this.data.loading) {
      return
    }
    if (this.data.hasNext) {
      const params = {
        orderStatus: self.data.currentTab,
        pageIndex: self.data.pageIndex,
        pageSize: self.data.pageSize
      }
      if (isPull) {
        this.setData({
          loading: true
        })
      }

      orderModel
        .getOrderList(params)
        .then(res => {
          const tempArray = this.data.orderList.concat(res.data.orderList)
          if(res.data.hasNext){
            self.setData({
              pageIndex:self.data.pageIndex + 1
            })
          }
          self.setData({
            orderList: tempArray,
            hasNext: res.data.hasNext,
            loading: false
          })
        })
        .catch()
    } else {
      App.WxService.showToast({
        title: '没有更多数据了',
        icon: 'none'
      })
      return
    }
  },

  //上滑到底
  lower: function() {
    if(this.data.hasNext && this.data.pageIndex == 1){
      this.setData({
        pageIndex:this.data.pageIndex + 1
      })
    }
    // this.data.pageIndex = this.data.pageIndex + 1
    this.loadMore(true)
  },

  /**
     * 页面上拉触底事件的处理函数
     */
  onReachBottom: function() {}
})
